package com.ywgt.controller;

import com.github.pagehelper.Page;
import com.ywgt.pojo.Admin;
import com.ywgt.pojo.Brand;
import com.ywgt.pojo.Category;
import com.ywgt.service.AdminService;
import com.ywgt.service.BrandService;
import com.ywgt.service.CategoryService;
import com.ywgt.util.ResponseUtil;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/admin/brand")
@ApiModel("品牌管理")
public class BrandController {
    @Autowired
    BrandService brandService;
    /**
     * page: 1,
     *limit: 20,
     *id: undefined,
     * name: undefined,
     * sort: 'add_time',
     *  order: 'desc'
     * @return
     */
    @GetMapping("/list")
    public Object getBrands(String name, Integer id, @RequestParam(required = false,defaultValue = "add_time") String sort,
                            @RequestParam(required = false,defaultValue = "desc") String order,
                            @RequestParam(required = false,defaultValue = "1") int page,
                            @RequestParam(required = false,defaultValue = "10") int limit){
        Page<Brand> brands=brandService.getBrands(name,id,page,limit,sort,order);
        List<Brand> items = brands.getResult().stream().filter(brand -> !brand.getDeleted()).collect(Collectors.toList());
        long total = brands.getTotal();
        Map<String,Object> data=new HashMap<>();
        data.put("total",total);
        data.put("items",items);
        return ResponseUtil.ok(data);
    }

    @GetMapping("/catAndAdmin")
    public Object catAndAdmin(){
        return brandService.catAndAdmin();
    }

    @PostMapping("/update")
    public Object update(@RequestBody Brand brand){
        if(brandService.updateById(brand)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody Brand brand){
        Map<String,Object> del=new HashMap<>();
        del.put("id",brand.getId());
       if(brandService.removeByMap(del)){
           return ResponseUtil.ok();
       }
       return ResponseUtil.fail();
    }

    @PostMapping("/create")
    public Object create(@RequestBody Brand brand){
        System.out.println(brand);
        if(brandService.save(brand)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }
}
